package org.su.webadapter.render;

import org.su.generalmvc.IModel;
import org.su.generalmvc.render.IRender;
import org.su.webadapter.velocity.HtmlHelper;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用action结果数据渲染velocity视图。返回正确的html内容到浏览器
 * 
 * @author yangchuan 2010-8-26 下午03:23:34
 * 
 */
public class VelocityRender implements IRender {

	@Override
	public void render(IModel model, Object result, String defaultPath,
			ServletRequest request, ServletResponse response) {
           String path = (String) result;
		try {
			if (StringUtils.isNotBlank(path)) {
				if (path.startsWith("f:")) {
					request.getRequestDispatcher(path.substring(2)).forward(
							request, response);
					return;
				}

				if (path.startsWith("r:")) {
					String str = path.substring(2);
					if(str.startsWith("http")){
                        ((HttpServletResponse)response).sendRedirect(str);
					}else{
						String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+((HttpServletRequest)request).getContextPath()+"/";
                        ((HttpServletResponse)response).sendRedirect(basePath + str);
					}
					
					return;
				}
			} else {
				path = defaultPath;
			}
			
			if (!path.startsWith("pages/")) {
				if (path.startsWith("/")) {
					path = "pages" + path;
				} else {
					path = "pages/" + path;
				}
			}

			Map<String, ?> data = null;
			if (model != null) {
				data = model.getModel();
			}
			HtmlHelper.INSTENCE.generateHtml(data, path, request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
